package com.dzu.medium;

/**
 * @author ZhaoDong
 * @date 2022/11/14 15:45
 * @description 477. 汉明距离总和
 */
public class Test477 {
    public static void main(String[] args) {
        System.out.println(totalHammingDistance2(new int[]{4, 14, 2}));
    }

    public static int totalHammingDistance2(int[] nums) {
        int ans = 0;
        for (int x = 31; x >= 0; x--) {
            int s0 = 0, s1 = 0;
            for (int u : nums) {
                if (((u >> x) & 1) == 1) {
                    s1++;
                } else {
                    s0++;
                }
            }
            ans += s0 * s1;
        }
        return ans;

    }

    // 暴力
    public static int totalHammingDistance(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int ni = nums[i];
                int nj = nums[j];
                count += Integer.bitCount(ni ^ nj);
            }
        }

        return count;
    }
}
